
package com.game;

import com.game.sprite.*;
import net.obviam.droidz.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Classe do jogo, usada na classe principal que herda de Activity, que seria equivalente ao Program do C#/XNA
 * @author Harmonia Game Studio
 * Extende / herda de surface view, afinal as coisas aparecem (onDraw), e implementa (tipo de herana mœltipla)
 * de surface holder, afinal, responde ao toque (ver mŽtodo)
 */
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback
{

	/**
	 * ...
	 */
	private static final String TAG = MainGamePanel.class.getSimpleName();

	/**
	 * chama update e draw
	 */
	private MainThread thread;

	/**
	 * imagem
	 */
	private SpriteAnimated sprite;

	private SpriteFont spriteFont;


	private float offsetX;
	private float offsetY;
	
	private Explosion currentExplosion;
	
	/**
	 * 
	 * construtor
	 * @param context
	 */
	public MainGamePanel(Context context)
	{
		//passa ao pai o "contexto
		super(context);

		// •ntercepta os eventos
		getHolder().addCallback(this);

		// criaao do objeto e carregamento da imagem
		sprite = new SpriteAnimated(BitmapFactory.decodeResource(getResources(), R.drawable.mariowalk), 50, 50,16,50,3,3);

		spriteFont = new SpriteFont(BitmapFactory.decodeResource(getResources(), R.drawable.fontebranca));

		// cria a thread principal
		thread = new MainThread(getHolder(), this);

		//tr‡s o jogo "pra frente" pra receber os eventos de toque, etc
		setFocusable(true);
	}

	/**
	 * temos que implementar este método pois herdamos de surfaceholder
	 * @param holder
	 * @param format
	 * @param width
	 * @param height
	 */
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,	int height)
	{
		//nada...
	}

	/**
	 * temos que implementar este mŽtodo pois herdamos de surfaceholder
	 * @param holder
	 */
	@Override
	public void surfaceCreated(SurfaceHolder holder)
	{

		//neste momento a superf’cie/estrutura de desenho est‡ criada
		//e podemos chamar o game loop:
		thread.setRunning(true);
		thread.start();
	}

	/**
	 * 
	 * @param holder
	 */
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) 
	{
		Log.d(TAG, "surfaceDestroyed");

		//diz pra thread desligar e espera ela acabar por garantia
		//economia de mem—ria, celular, performance

		boolean retry = true;

		while (retry)
		{
			try 
			{
				thread.join();
				retry = false;
			}
			catch (InterruptedException e)
			{
				// continua tentando desligar a thread / processo / game
			}
		}

		Log.d(TAG, "surfaceDestroyed OK");
	}

	/**
	 * evento de toque na tela, testa com mouse no comp
	 * 
	 * @param event
	 * @return
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		//se cliquei
		if (event.getAction() == MotionEvent.ACTION_DOWN)
		{
			// mando o sprite fazer algo com isso, passo a posicao do clique

			offsetX = sprite.getX() - event.getX();
			offsetY = sprite.getY() - event.getY();
			sprite.handleActionDown((int)event.getX(), (int)event.getY());
			
			if(currentExplosion == null || currentExplosion.isDead()){
				currentExplosion = new Explosion(100, (int)event.getX(), (int)event.getY(),.25f);
			}

			//se cliquei em certa posicao da tela, muito embaixo
			if (event.getY() > getHeight() - 50) 
			{
				//saio
				thread.setRunning(false);
				((Activity)getContext()).finish();
			}
			else //senao
			{
				//printo onde cliquei
				Log.d(TAG, "Coords: x=" + event.getX() + ",y=" + event.getY());
			}			
		}

		//se movi o dedo
		if (event.getAction() == MotionEvent.ACTION_MOVE)
		{
			// se o sprite tiver tocado
			if (sprite.isTouched())
			{
				// movo...
				sprite.setX((int)(event.getX() + offsetX));
				sprite.setY((int)(event.getY() + offsetY));
			}

		}

		//se larguei o dedo
		if (event.getAction() == MotionEvent.ACTION_UP) 
		{
			// se o sprite tava tocado
			if (sprite.isTouched()) 
			{
				//nao est‡ mais
				sprite.setTouched(false);
			}
		}

		return true;
	}

	/**
	 * mŽtodo de desenho
	 * 
	 * @param canvas, meu spriteBatch
	 */
	@Override
	protected void onDraw(Canvas canvas) 
	{
		//limpeza da tela
		canvas.drawColor(Color.BLACK);

		//desenha um sprite
		sprite.draw(canvas);

		if ( teste < 100){
			spriteFont.drawString(canvas, "FACE", 100, 100);
			teste++;
		}
		
		
		if(currentExplosion != null && currentExplosion.isAlive()){
			currentExplosion.draw(canvas);
		}
	}

	private int teste = 0;

	
	public void onUpdate(long gameTime){
		
		sprite.Update(gameTime);
		
		Log.d(TAG, "hjhh");
		
		if(currentExplosion != null && currentExplosion.isAlive()){
			currentExplosion.update(getHolder().getSurfaceFrame());
		}
	}
}
